<template>
  <div style="height: 100%">
    <el-card>
      <div class="mag_t-10">
        <el-form :model="SearcOrder" label-width="auto">
          <div class="wh_f">
            <div class="flex_1">
              <el-form-item label="来源 :">
                <el-select v-model="SearcOrder.source" placeholder="请选择订单来源">
                  <el-option v-for="(item,index) in vuex.shopClsssList.value" :key="index"
                             :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </div>
            <div class="flex_1">
              <el-form-item
                  class="mag_l-10" label="订单日期 :">
                <el-date-picker
                    v-model="SearcOrder.time"
                    type="daterange"
                    unlink-panels
                    range-separator="To"
                    start-placeholder="开始日期"
                    end-placeholder="结束时间"
                    :shortcuts="shortcuts"
                    :size="size"
                />
              </el-form-item>
            </div>
            <div class="flex_2">
              <el-button @click="getOrder_list" class="mag_l-30" type="primary">查询</el-button>
              <el-button @click="Clear" type="primary">重置</el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>

    <el-card class="mag_t-20">
      <el-button @click="addShop" type="primary">添加订单</el-button>
      <div class="coll_title mag_t-20">订单列表</div>
      <div>
        <el-table v-if="tableData" :data="tableData" :border="true">
          <el-table-column type="selection" width="40" />
          <el-table-column prop="id" label="ID" width="50" />
          <el-table-column prop="goods_name" label="名称" width="100" />
          <el-table-column prop="age" label="单价" width="100" />
          <el-table-column prop="sum" label="数量" width="100" />
          <el-table-column prop="money" label="总价" width="100" />
          <el-table-column prop="addmoney" label="进价" width="100" />
          <el-table-column prop="profit_age" label="利润" width="100" />
          <el-table-column prop="source_name" label="来源" width="100" />
          <el-table-column prop="createtime" label="时间" width="220" />
          <el-table-column label="操作" min-width="120">
            <template #default="scope">
              <el-button type="primary">查看</el-button>
              <el-button type="primary" @click="updaClick(scope.row)">编辑</el-button>
              <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确定删除此订单吗?"
                  @confirm="deleteData(scope.row)"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <div class="demo-pagination-block pad_t_20">
          <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[10, 20, 30, 100]"
              :size="size"
              :disabled="disabled"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="count"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <el-dialog v-model="visible" :show-close="false" width="1300px">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div class="wh_f">
            <div class="flex_1"><h4 :id="titleId" :class="titleClass">{{ title }}</h4></div>
            <div><el-button type="danger" @click="close">X</el-button></div>
          </div>
        </div>
      </template>
      <div>
        <div class="wh_f">
          <div class="flex_3">
            <titleText title="产品分类"></titleText>
            <div class="ccgl">
              <selectDiv @selectDiv="selecFunction" title="产品分类" :data="shopClsssList"></selectDiv>
            </div>
            <div>
              <div class="disp" v-for="(item,index) in shopList" style="width: 10%" :key="index">
                <el-button @click="selectAge(item)" class="wh_9 mag_t_10 pad_20_0" type="primary">{{item.name}}</el-button>
              </div>
            </div>
          </div>
          <div class="flex_2 pad_0_20 boxs">
            <titleText title="销售来源"></titleText>
            <selectDiv @selectDiv="selecFunction" ref="SelectDivchildren" title="销售来源"
                       :data="SourceList"></selectDiv>
            <div class="split_2_8">
              <div class="centerdq"><titleText title="自动抹零"></titleText></div>
              <div class="centerdq"><el-switch class="mag_l-5" v-model="moneyIntValue" /></div>
            </div>
            <titleText title="产品信息"></titleText>
            <div class="wh_f">
              <div class="flex_1">
                <el-form :model="form" :rules="rules"  ref="formRef" label-width="auto" style="max-width: 200px">
                  <el-form-item label="产品:" prop="name">
                    <el-input disabled v-model="form.name"/>
                  </el-form-item>
                  <el-form-item label="单价:" prop="age">
                    <el-input-number @input="computeMoney1" v-model="form.age" :min="1" @change="handleChange" />
                  </el-form-item>
                  <el-form-item label="数量:" prop="sum">
                    <el-input @input="computeMoney2" v-model="form.sum" />
                  </el-form-item>
                  <el-form-item label="总价:" prop="money">
                    <el-input-number :min="1" v-model="form.money" />
                  </el-form-item>
                  <el-form-item v-if="title=='编辑订单'" label="进价:" prop="addmoney">
                    <el-input-number :min="1" v-model="form.addmoney" />
                  </el-form-item>
                  <el-form-item v-if="title=='编辑订单'" label="利润:" prop="profit_age">
                    <el-input-number :min="1" v-model="form.profit_age" />
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="moneyInt" type="primary">抹零</el-button>
                    <el-button @click="postOrder" type="success">确认</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div class="flex_1 wz_white">
                <div class="split_3_3">
                  <div>
                    <div @click="addAge(7)" class="age_button ba_mhl">7</div>
                  </div>
                  <div>
                    <div @click="addAge(8)" class="age_button ba_mhl">8</div>
                  </div>
                  <div>
                    <div @click="addAge(9)" class="age_button ba_mhl">9</div>
                  </div>
                </div>
                <div class="split_3_3 mag_t-10">
                  <div>
                    <div @click="addAge(4)" class="age_button ba_mhl">4</div>
                  </div>
                  <div>
                    <div @click="addAge(5)" class="age_button ba_mhl">5</div>
                  </div>
                  <div>
                    <div @click="addAge(6)" class="age_button ba_mhl">6</div>
                  </div>
                </div>
                <div class="split_3_3 mag_t-10">
                  <div>
                    <div @click="addAge(1)" class="age_button ba_mhl">1</div>
                  </div>
                  <div>
                    <div @click="addAge(2)" class="age_button ba_mhl">2</div>
                  </div>
                  <div>
                    <div @click="addAge(3)" class="age_button ba_mhl">3</div>
                  </div>
                </div>
                <div class="split_3_3 mag_t-10">
                  <div>
                    <div @click="addAge(0)" class="age_button ba_mhl">0</div>
                  </div>
                  <div>
                    <div @click="addAge('.')" class="age_button ba_mhl jdz">.</div>
                  </div>
                  <div>
                    <div @click="addAge('-')" class="age_button ba_mhl">删除</div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">
// 引用状态存储
import { storeVuex } from "@/store/modules/user";
import {storeToRefs} from "pinia";
const vuex = storeToRefs(storeVuex())
import { order,shop_type } from '@/api/index'
import {onMounted, reactive, ref, watch} from "vue";

// 使用 ref 创建一个引用来访问子组件
const SelectDivchildren = ref(null);

// 弹窗标题
let title = ref("")
let source_id = ref()

// 引入封装的全局消息提示
import { getCurrentInstance } from 'vue';
import {ElMessage} from "element-plus";
let { proxy }:any = getCurrentInstance(); // 获取当前实例的代理


/*页面初始化执行*/
onMounted(() => {
  // 查询订单
  getOrder_list(); // 默认执行 initChart 方法
  /*获取商品*/

  // 获取商品分类列表
  getShop_clsss();
  // 获取订单来源列表
  getSourceList();
});


// 清除搜索条件
const Clear = ()=>{
    SearcOrder.source = null
    SearcOrder.time = []
}
// 分页
const handleSizeChange = async ()=>{
  getOrder_list();
}
const handleCurrentChange = async ()=>{
  getOrder_list();
}
// 删除订单
const deleteData = async (e:any)=>{
  const res= await order.deleteOrder({id:e.id})
  ElMessage({
    message: res.data.msg,
      type: res.data.status==1?'success':'error'
  })
  getOrder_list();
}
//校验规则
const rules = reactive({
  name: [
    { required: true, message: '请选择产品', trigger: 'blur' }
  ],
  sum: [
    { required: true, message: '请输入数量', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入单价', trigger: 'blur' }
  ],
  money: [
    { required: true, message: '请输入总价', trigger: 'blur' }
  ],
})
// 弹窗开关
let visible = ref(false)
// 自动抹零开关
let moneyIntValue = ref(true)
// 产品分类选项卡值
let activeName = ref()
// 来源分类选项卡值
let sourceName = ref()
//模拟来源列表数据
let sourceList = ref([
    {id:1,title_name:'菜市场'},
    {id:2,title_name:'饭店'},
    {id:3,title_name:'咸鱼'}
])
// 订单列表
let tableData = ref([])
// 产品信息
const shop = reactive({})
// 价格计算的表单数据
let form:any = reactive({
  addmoney:null,
  age:null,
  money:null,
  name:null,
  shopType:null,
  shopType_id:null,
  shop_id:null,
  sum:null
})
//产品列表
let shopList = ref([])
//产品分类列表
let shopClsssList = reactive([])
//订单来源列表
let SourceList = reactive([])
// 监听小键盘控制的价钱发生变化 重新计算值
watch(
    () => form.sum,(newValue,oldValue)=>{
      computeMoney2(form.sum)
})
const addAge = (e:any)=>{
  if(e=='-'){
      form.sum = form.sum.slice(0,-1)
  }else{
    if(form.sum==null){
      form.sum = e
    }else{
      form.sum +=String(e)
    }
  }
}

let page = ref(1)
let limit = ref(10)
let count = ref()

// 使用 ElForm 的 validate 方法进行验证
let formRef = reactive({});
//提交订单
const postOrder = async ()=>{
  // @ts-ignore
  formRef.validate(async (valid: any) => {
    if (valid) {
      if(title.value=='添加订单'){
        form.shop_id = vuex.userType_id.value
        const res = await order.addOrder(form);
        const ok = proxy.$showMessage(res.data.status, res.data.msg); // 调用全局方法来输出接口请求结果
        if (ok) {
          await getOrder_list();//查询订单列表
          clearForm();//添加成功, 清空产品数据
        }
      }else{
        const res = await order.updaOrder({
          id:form.id,
          age:form.age,
          sum:form.sum,
          money:form.money,
          source:form.source,
          addmoney:form.addmoney,
          profit_age:form.profit_age,
        });
        const ok = proxy.$showMessage(res.data.status, res.data.msg); // 调用全局方法来输出接口请求结果
        if (ok) {
          await getOrder_list();//查询订单列表
          clearForm();//修改成功, 清空产品数据
        }
        console.log('请求数据',form)
      }
    } else {
      proxy.$showMessage(0, '请输入完整的数据');
      return false;
    }
  });

}
//清空产品数据
const clearForm = ()=>{
  console.log('清楚前',form)
  form.addmoney = null,
  form.age = null,
  form.money = null,
  form.name = null,
  form.shopType_id = null,
  form.shop_id = null,
  form.sum = null
}
// 数量输入框发生改变计算价格
const computeMoney1 = (e:any)=>{
  form.money = parseFloat(e)*parseFloat(form.sum)
  form.money = parseFloat(form.money).toFixed(2)
}
// 数量输入框发生改变计算价格
const computeMoney2 = (e:any)=>{
    form.money = parseFloat(e)*parseFloat(form.age)
  if(moneyIntValue.value){
    form.money = parseFloat(form.money).toFixed(0)
  }else{
    form.money = parseFloat(form.money).toFixed(2)
  }
}
// 抹零
const moneyInt = ()=>{
  form.money = parseInt(form.money)
  form.money = parseFloat(form.money).toFixed(2)
}
//滑块选择器值的回调函数
const selecFunction = (title:any,id:any)=>{
  switch (title){
    case "产品分类":
      getShop_type(id)
      break;
    case "销售来源":
      form.source = id
      break;
  }
}
// 点击添加订单 清除表单初始值
const addShop = ()=>{
  visible.value =! visible.value
  form.age = null
  form.sum = null
  form.money = null
  // @ts-ignore
  form.source = SourceList[0].id
  title.value = '添加订单'
}

const getSourceList = async ()=>{
  const res: any = await order.getSourceList({
    shop_id: vuex.userType_id.value,
  })
  SourceList = res.data.data.data
}
const danJia = ref()
// 点击单价加减事件
const handleChange = (value: number) => {
  // danJia.value += 0.5;
}
// 产品价格
const selectAge = (e:any)=>{
  console.log(e)
  form.name = e.name
  form.addmoney = e.addmoney
  form.age = e.age
  form.shopType_id = e.id
  computeMoney1(form.age)
}
//获取产品分类
const getShop_type = async (e:any)=> {
  const res: any = await shop_type.getShop_type({
    shop_id: vuex.userType_id.value,
    type: e,
    is_show:1
  })
  shopList.value = res.data.data.data
}
const getShop_clsss = async () => {
    const res: any = await shop_type.getShop_class({
      shop_id: vuex.userType_id.value
    })
    // 产品分类选项卡值默认为第一个产品
    activeName = res.data.data.data[0].id
    // 拿到分类id 去查询产品分类
    getShop_type(activeName)
    // 所有产品分类列表
    shopClsssList = res.data.data.data
  }
// 点击产品分类 此时应该查询该分类下的产品数据
const updaClick = (e:any) => {
    console.log('订单信息',e)
    title.value = '编辑订单'
    visible.value = true
    form = e
    form.name = e.goods_name

    /*调用子组件方法 给组件传值来源*/
    // @ts-ignore
    SelectDivchildren.value.SelectDivindex(e.source)
  }
  //获取订单列表
const getOrder_list = async () => {
    const res: any = await order.getOrderList({
      page: page.value,
      limit: limit.value,
      shop_id:vuex.userType_id.value,
      startTime:SearcOrder.time[0]?SearcOrder.time[0]:null,
      endTime:SearcOrder.time[1]?SearcOrder.time[1]:null,
      source:SearcOrder.source?SearcOrder.source:null
    })
    tableData.value = res.data.data.data
    page.value = res.data.data.page
    limit.value = res.data.data.limit
    count.value = res.data.data.count
  }
// 搜索条件数据
let SearcOrder = reactive({
  time:[],
  source:null
})
</script>
<style>
.age_button{
  width: calc(100% - 10px);
  text-align: center;
  border-radius: 5px;
  padding: 10px 0;
  box-sizing: border-box;
  cursor: pointer;
}
.ba_mhl{
  background-color: #0069df;
}
.ba_mhl:hover{
  background-color: #e8e4e4;
  color: black;
}
</style>
<style scoped>
nav{
  position: relative;
  height: 50px;
}
nav a{
  /*padding: 5px 0;*/
  position: relative;
  display: block;
  float: left;
  line-height: 50px;
  height: 50px;
  text-transform: uppercase;
  text-decoration: none;
  text-align: center;
  z-index: 10;
  font-weight:bold;
  user-select:none;
}
nav a{
  width: 120px;
  font-weight: normal;
  font-size: 18px;
  color: white;
}
nav .animation{
  position: absolute;
  height: 100%;
  width: 120px;
  background-color: #4f80f0;
  z-index: 9;
  border-radius: 8px;
  transition: all 0.3s;
}
.start-zixun,
nav a:nth-child(1):hover~.animation{
  width: 120px;
  left: 0;
}
.start-zhongzhi,
nav a:nth-child(2):hover~.animation{
  width: 120px;
  left: 120px;
}
.start-gaozhi,
nav a:nth-child(3):hover~.animation{
  width: 120px;
  left: 240px;
}
</style>
